package com.soft.mainsite.component.beetl.tag.topic;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.utils.Pojo2MapUtil;
import com.soft.mainsite.common.utils.StrUtil;
import com.soft.mainsite.module.publishlog.service.PublishLogService;
import com.soft.mainsite.module.web.cms.service.CategoryService;
import com.soft.mainsite.module.web.cms.service.SiteService;
import com.soft.mainsite.module.web.cms.service.TopicService;
import com.soft.mainsite.mybatis.model.TCmsCategory;
import com.soft.mainsite.mybatis.model.TCmsSite;
import com.soft.mainsite.mybatis.model.TCmsTopic;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * TopicCategoryListTag.java 此类用于专题栏目列表tag
 * 根据topicId获取栏目id
 *
 * @author:李昭阳
 * @date:2019/4/28 0028
 * @remark:
 */
@Slf4j
@Service
@Scope("prototype")
public class TopicInfoTag extends GeneralVarTagBinding {

    @Autowired
    private TopicService topicService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PublishLogService publishLogService;

    @Autowired
    private SiteService siteService;

    @Value("${system.http.protocol}")
    private String httpProtocol;

    @Value("${system.http.host}")
    private String httpHost;

    @Value("${system.site.prefix}")
    private String sitePrefix;

    @Value("${system.site.subfix}")
    private String siteSubfix;

    @Override
    public void render() {
        Integer onlyChild = Convert.toInt(this.getAttributeValue("onlyChild"));
        Integer topicId = Convert.toInt(this.getAttributeValue("topicId"));
        Integer siteId = Convert.toInt(this.getAttributeValue("siteId"));
        if (topicId == null) {
            throw new CmsException("查询topic信息时topicId不能为空！！");
        }
        try {
            this.wrapRender(topicId, onlyChild, siteId);
        } catch (Exception e) {
            log.error("专题栏目列表渲染失败，专题id:{}", topicId, e);
            publishLogService.save(siteId, null, "", "专题栏目列表渲染失败，专题id:" + topicId);
            throw new CmsException("专题栏目列表渲染失败");
        }
    }

    private void wrapRender(Integer topicId, Integer onlyChild, Integer siteId) throws Exception {
        TCmsTopic topic = topicService.findById(topicId);
        HttpServletRequest request = (HttpServletRequest) ctx.getGlobal("request");
        String[] categoryIds = topic.getCategoryIds().split(",");

        if (ArrayUtil.isEmpty(categoryIds)) {
            return;
        }

        Map result = Pojo2MapUtil.toMap(topic);
        for (String str : categoryIds) {
            TCmsCategory category = categoryService.findById(Long.valueOf(str));
            TCmsSite site = siteService.findById(siteId);

            if (category == null) {
                throw new CmsException("category栏目不存在！！");
            }

            if (category.getHasChild() != null){
                if (Convert.toBool(category.getHasChild()) && onlyChild == 1) {
                    continue;
                }
            }

            result.put("url", !StrUtil.isBlank(category.getUrl()) ? category.getUrl() : request.getContextPath() + "/" + site.getSiteKey() + "/" + category.getAlias() + siteSubfix);
            result.put("categoryName", category.getCategoryName());
            result.put("categoryId", category.getCategoryId());
            result.put("categoryUrl", category.getUrl());
            result.put("categoryIcon", category.getCategoryIcon());
            result.put("categoryAlias", category.getAlias());

            this.binds(result);
            this.doBodyRender();
        }

    }
}
